<template>
  <el-upload
    ref="uploadRef"
    v-model:file-list="fileList"
    :action="url"
    :limit="limit"
    :auto-upload="autoUpload"
    :accept="'.' + fileTypes.join(',.')"
    :on-preview="handlePreview"
    :on-exceed="handleExceed"
    :on-change="onFileChange"
    :on-success="onSuccess"
    :on-remove="onRemove"
  >
    <el-button type="primary">选择文件</el-button>
    <template #tip>
      <div class="el-upload__tip">jpg/png files with a size less than 500KB.</div>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, type UploadFile } from 'element-plus'

import type { UploadProps, UploadUserFile } from 'element-plus'
import { onMounted, ref, watch } from 'vue'

interface Props {
  url: string
  limit: number
  fileTypes: string[]
  maxSize: number
  autoUpload: boolean
  files: UploadUserFile[]
}

interface Emits {
  (e: 'success', fileId: string): void

  (e: 'remove', fileId: string): void

  (e: 'all'): void
}

const props = withDefaults(defineProps<Props>(), {
  url: '/api/upload',
  limit: 10,
  fileTypes: () => ['zip', 'jpg', 'png'],
  maxSize: 100 * 1024,
  autoUpload: false,
  files: () => []
})

const emits = defineEmits<Emits>()
const uploadRef = ref()
const fileList = ref<UploadUserFile[]>(props.files)

watch(
  () => props.fileTypes,
  () => (fileList.value = props.files)
)

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  )
}

const onFileChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile)
}

const onRemove = (uploadFile: UploadFile) => {
  emits('remove', uploadFile.uid)
}

const onSuccess = (response: string) => {
  console.log('--- 上传完成')
  emits('success', response)

  const lenght = fileList.value.filter((file: UploadUserFile) => {
    return file.status === 'ready' || file.status === 'uploading'
  }).length

  if (lenght === 0) {
    emits('all')
  }
}

const upload = () => {
  uploadRef.value?.submit()
}

const getWaitFileLength = () => {
  return fileList.value.filter((file: UploadUserFile) => {
    return file.status === 'ready'
  }).length
}

defineExpose({ upload, fileList, getWaitFileLength })
</script>

<style scoped lang="less"></style>
